<script setup>
import { ref, reactive, watch, onMounted, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deviceApi as MainApi, deviceById as MainById } from '@T2/service/api.ts';
import { useIuserInfoStore } from '@T2/store/users.ts';
import WarnSet from '../components/warnSet.vue';
import Detail from './components/detail.vue';
import AddEdit from './components/addEdit.vue';
import ExportExcel from './components/exportExcel.vue';

const iuserInfoStore = useIuserInfoStore();
const { getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['346', '347', '348', '349']);

const props = defineProps({
  unit: {
    type: Object,
    required: true,
  },
  ifUnitMul: {
    type: Boolean,
    required: true,
  }
});
const emits = defineEmits(['pagesChange']);

onMounted(() => {
  GetMainTable();
});
watch(() => props.unit.id, (nv) => {
  if (nv) {
    GetMainTable();
  }
})

const MainTable = reactive({
  data: [],
  total: 0,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  search: '',
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainTable.data = [];
  if (!props.unit.id) {
    return;
  }
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      unit: props.unit?.id,
      front_delete: false,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  type: '',
  unit: null,
  content: null,
});
const changeMainPopupType = (isAble = false, type, row = null) => {
  if (!isAble) {
    return;
  }
  if (!props.unit?.id) {
    ElMessage.error('未知故障！');
    return;
  }
  MainPopup.type = type;
  MainPopup.content = row;
  MainPopup.unit = props.unit.id;
}
const handleMainDelete = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'patch',
      id: row.id,
      data: {
        front_delete: true,
      }
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

/* 详情 */
const detailPopup = reactive({
  content: {},
});
const handleDetailPopup = (row) => {
  detailPopup.content = row;
}
const addEditClose = (refresh) => {
  MainPopup.type = '';
  if (refresh) {
    GetMainTable();
  }
}

/* 报警配置 */
const warnSetInfo = ref(null);
const warnPopupSet = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  warnSetInfo.value = row;
}
</script>

<template>
  <div class="deviceList-box flex-column mainCard">
    <div class="header-lines flex-sb-center">
      <div class="flex--center">
        <label class="header" v-show="props.ifUnitMul">设备台账</label>
        <el-form label-width="0" class="flex t_form">
          <el-form-item label="" style="margin-bottom: 0;">
            <el-input placeholder="查询设备：" v-model="Filter.search" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex--center">
        <ExportExcel :unit="props.unit" />
        <el-button type="primary" @click="changeMainPopupType(RIGHT['346'], '新增')" :disabled="!RIGHT['346']">新增</el-button>
      </div>
    </div>
    
    <el-table :data="MainTable.data" scrollbar-always-on>
      <el-table-column label="设备位号" prop="code" width="120px"></el-table-column>
      <el-table-column label="设备名称" prop="name" min-width="160px" show-overflow-tooltip></el-table-column>
      <el-table-column label="安装位置" prop="addr" min-width="160px" show-overflow-tooltip></el-table-column>
      <el-table-column label="投运日期" prop="use_time" min-width="120px"></el-table-column>
      <el-table-column label="维保周期" prop="cycle" min-width="100px"></el-table-column>
      <el-table-column label="产品名称" prop="product_name" min-width="160px" show-overflow-tooltip></el-table-column>
      <el-table-column label="规格型号" prop="product_gg" min-width="160px" show-overflow-tooltip></el-table-column>
      <el-table-column label="品牌" prop="brand" min-width="120px"></el-table-column>
      <el-table-column label="备注" prop="remark" min-width="160px" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" fixed="right" width="180px">
        <template #default="scope">
          <!-- <el-button link type="primary" @click="warnPopupSet(RIGHT['349'], scope.row)" :disabled="!RIGHT['349']">
            告警配置
          </el-button> -->
          <el-button link type="primary" @click="handleDetailPopup(scope.row)">详情</el-button>
          <el-button link type="primary" @click="changeMainPopupType(RIGHT['347'], '编辑', scope.row)" :disabled="!RIGHT['347']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleMainDelete(RIGHT['348'], scope.row)" :disabled="!RIGHT['348']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      layout="->, total, prev, pager, next, sizes"
      background 
      :page-sizes="[10, 20, 30, 50, 100]"
      :pager-count="5"
      v-model:currentPage="Filter.page"
      v-model:page-size="Filter.pagesize"
      :total="MainTable.total"
    />
  </div>
  
  <AddEdit
    v-if="MainPopup.type"
    :type="MainPopup.type"
    :unit="MainPopup.unit"
    :content="MainPopup.content"
    @close="addEditClose"
  />
  
  <Detail
    v-if="detailPopup.content?.id"
    :content="detailPopup.content"
    @close="detailPopup.content = {}"
  />
  
  <WarnSet :device="warnSetInfo" @closed="warnSetInfo = null" />
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.deviceList-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.header-lines {
  width: 100%;
  margin-bottom: 24px;
  label.header {
    font-weight: 400;
    font-size: 16px;
    color: #0079FE;
    height: 30px;
    line-height: 22px;
    position: relative;
    white-space: nowrap;
    margin-right: 10px;
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 2px;
      background-color: #0079FE;
    }
  }
}
</style>